//
//  UserAccount.swift
//  iOS07-Weibo-LPK
//
//  Created by 罗培克 on 6/26/15.
//  Copyright © 2015 lpk. All rights reserved.
//

import UIKit

class UserAccount: NSObject, NSCoding{
    
    var access_token: String
    var expires_in: NSTimeInterval
    var expiresDate: NSDate
    var uid: String
    /// 友好显示名称
    var name: String?
    /// 用户头像地址
    var avatar_large: String?
    
    // 归档路径, static 用于定义常量
    static let accountPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last!.stringByAppendingPathComponent("account.plist")
    
    /// 加载用户信息
    func loadUserInfo(finished: (account: UserAccount?, error: NSError?) -> ()) {
        let params = ["access_token": access_token, "uid": uid]
        NetworkTools.sharedNetworkTools().GET("2/users/show.json", parameters: params, success: { (_, json) -> Void in
            let dict = json as! [String: AnyObject]
            
            self.name = dict["name"] as? String
            self.avatar_large = dict["avatar_large"] as? String
            
            // 此时的用户信息才是完整的,需要在这里保存
            self.saveAccount()
            
            // 完成回调
            finished(account: self, error: nil)
            
            }) { (_, error) -> Void in
                finished(account: nil, error: error)
        }
    }
    
    /// 将当前对象归档保存至沙盒
    func saveAccount() {
        NSKeyedArchiver.archiveRootObject(self, toFile: UserAccount.accountPath)
    }
    
    /// 从沙盒加载 account
    class func loadAccount() -> UserAccount? {
        // 如果之前没有归档,会返回 nil, 不会进入 if 里面
        if let account = NSKeyedUnarchiver.unarchiveObjectWithFile(UserAccount.accountPath) as? UserAccount {
            // 比较结果是"降序",说明过期日期大于当前日期
            if account.expiresDate.compare(NSDate()) == NSComparisonResult.OrderedDescending {
                return account
            }
        }
        
        return nil
    }
    
    init(dict: [String: AnyObject]) {
        access_token = dict["access_token"] as! String
        expires_in = dict["expires_in"] as! NSTimeInterval
        expiresDate = NSDate(timeIntervalSinceNow: expires_in)
        uid = dict["uid"] as! String
    }
    
    override var description: String {
        let properties = ["access_token", "expires_in", "uid", "expiresDate", "name", "avatar_large"]
        return "\(self.dictionaryWithValuesForKeys(properties))"
    }
    
    /// 接归档
    required init(coder aDecoder: NSCoder) {
        access_token = aDecoder.decodeObjectForKey("access_token") as! String
        expires_in = aDecoder.decodeDoubleForKey("expires_in")
        expiresDate = aDecoder.decodeObjectForKey("expiresDate") as! NSDate
        uid = aDecoder.decodeObjectForKey("uid") as! String
        name = aDecoder.decodeObjectForKey("name") as? String
        avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
    }
    
    /// 归档
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeDouble(expires_in, forKey: "expires_in")
        aCoder.encodeObject(expiresDate, forKey: "expiresDate")
        aCoder.encodeObject(uid, forKey: "uid")
        aCoder.encodeObject(name, forKey: "name")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
    }
    
}
